package com.ktgj.customer.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.dto.CardDTO;
import com.ktgj.customer.domain.dto.CustomerCardDTO;
import com.ktgj.customer.domain.dto.CustomerRightdetailDTO;
import com.ktgj.customer.domain.dto.RightdetailDTO;
import com.ktgj.customer.mapper.*;
import com.ktgj.customer.service.ILoginService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.customer.service.ICardService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * 卡Service业务层处理
 *
 * @author ruoyi
 * @date 2021-07-30
 */
@Service
@Transactional
public class CardServiceImpl implements ICardService {
    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private CardRightdetailMapper cardRightdetailMapper;
    @Autowired
    private RightdetailMapper rightdetailMapper;
    @Autowired
    private ILoginService loginService;
    @Autowired
    private CustomerCardMapper customerCardMapper;

    /**
     * 查询卡
     *
     * @param cardId 卡ID
     * @return 卡
     */
    @Override
    public Card selectCardById(Long cardId) {
        Card card = cardMapper.selectCardById(cardId);
        return card;
    }

    /**
     * 查询卡及该卡下拥有的可用权益项
     *
     * @param cardId 卡ID
     * @return 卡
     */
    @Override
    public Card selectCardAndHaveRightdetailsById(Long cardId) {
        Card card = cardMapper.selectCardAndHaveRightdetailsById(cardId);
        return card;
    }

    /**
     * 查询卡列表
     *
     * @param card 卡
     * @return 卡
     */
    @Override
    public List<Card> selectCardList(Card card) {
        List<Card> lstCards = cardMapper.selectCardList(card);
        return lstCards;
    }

    /**
     * 新增卡
     *
     * @param card 卡
     * @return 结果
     */
    @Override
    public int insertCard(Card card, Employee employee) {
        int rows = 0;
        card.setCreateTime(DateUtils.getNowDate());
        card.setCreateEmployeeId(employee.getEmployeeId());
        card.setUpdateEmployeeId(employee.getEmployeeId());
        rows = cardMapper.insertCard(card);
        CardRightdetail cardRightdetailTmp = new CardRightdetail();
        List<CardRightdetail> lstCardRightdetail = cardRightdetailMapper.selectCardRightdetailList(cardRightdetailTmp);
        if (rows > 0) {
            for (Rightdetail rightdetail : card.getLstRightDetail()) {
                CardRightdetail tmpData = lstCardRightdetail.stream().filter(item -> item.getCardId() == card.getCardId() && item.getRightdetailId() == rightdetail.getRightdetailId()).findFirst().orElse(null);
                if (tmpData != null) {
                    CardRightdetail cardRightdetail = new CardRightdetail();
                    cardRightdetail.setCardId(card.getCardId());
                    cardRightdetail.setCardRightdetailId(rightdetail.getRightdetailId());
                    cardRightdetailMapper.insertCardRightdetail(cardRightdetail);
                    rightdetailMapper.insertRightdetail(rightdetail);
                }
            }
        }
        return rows;
    }

    /**
     * 修改卡
     *
     * @param card 卡
     * @return 结果
     */
    @Override
    public int updateCard(Card card) {
        card.setUpdateTime(DateUtils.getNowDate());
        int rows = 0;
        rows = cardMapper.updateCard(card);
        List<CardRightdetail> lstCardRightDetail = cardRightdetailMapper.selectCardRightdetailByCardId(card.getCardId());
        if (rows > 0) {
            for (Rightdetail rightdetail : card.getLstRightDetail()) {
                if (rightdetail.getRightdetailId() == null) {
                    CardRightdetail cardRightdetail = new CardRightdetail();
                    cardRightdetail.setCardId(card.getCardId());
                    cardRightdetail.setRightdetailId(rightdetail.getRightdetailId());
                    cardRightdetailMapper.insertCardRightdetail(cardRightdetail);
                    rightdetailMapper.insertRightdetail(rightdetail);
                }
            }
            for (CardRightdetail cardRightdetail : lstCardRightDetail) {
                if (card.getLstRightDetail().stream().noneMatch(item -> item.getRightdetailId() == cardRightdetail.getRightdetailId())) {
                    cardRightdetailMapper.deleteCardRightdetailById(cardRightdetail.getCardRightdetailId());
                }
            }
        }
        return rows;
    }

    /**
     * 批量删除卡
     *
     * @param cardIds 需要删除的卡ID
     * @return 结果
     */
    @Override
    public int deleteCardByIds(Long[] cardIds) {
        return cardMapper.deleteCardByIds(cardIds);
    }

    /**
     * 删除卡信息
     *
     * @param cardId 卡ID
     * @return 结果
     */
    @Override
    public int deleteCardById(Long cardId) {
        return cardMapper.deleteCardById(cardId);
    }

    @Override
    public List<CardDTO> queryPurchaseCardAndRightsDetail(HttpServletRequest request) {
        //查询出全部的卡类型（当前数据就是当前用户一张卡都没购买时候的原始数据）
        List<CardDTO> cardDTOS = cardMapper.selectCardAllDetails();

        Customer customer = loginService.getLoginCustomer(request);
        //查询出会员拥有的所有会员卡
        List<CustomerCardDTO> customerCards = customerCardMapper.selectCustomerCardByCustomerId(customer.getCustomerId());

        Long cardLevel = 0L;
        for (CardDTO card : cardDTOS) {
            //首先判断用户有没有购买这张卡,有的话就把用户的这张卡下拥有的权益取出来
            List<CustomerRightdetailDTO> customerRightdetailDTOS = null;
            a:
            for (int i = customerCards.size() - 1; i >= 0; i--) {
                CustomerCardDTO customerCard = customerCards.get(i);
                if (card.getCardId().equals(customerCard.getCardId())) {//用户有这张卡
                    card.setHave(true);
                    card.setCardCode(customerCard.getCardCode());
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
                    card.setIvalidDateString(dateFormat.format(customerCard.getInvalidDate()) + "到期·仅限本人使用");
                    if (card.getCardLevel() > cardLevel)
                        cardLevel = card.getCardLevel();
                    customerRightdetailDTOS = customerCard.getCustomerRightdetailDTOS();
                    customerCards.remove(i);//删除元素减轻循环压力
                    break a;//只会出现一张，没有继续的必要
                }
            }
            if (customerRightdetailDTOS == null)//代表用户没有这张卡
                card.setIvalidDateString("有效期一年·仅限本人使用");
            Long rightdetailNum = 0L;//记录当前会员卡可享几项权益
            for (RightdetailDTO rightdetail : card.getRightdetailDTOS()) {
                boolean isAscription = true;//判断该权益属于该卡
                if (!rightdetail.getAscriptionCardId().equals(card.getCardId())) {//该权益不属于该卡
                    isAscription = false;
                    for (int i = 0; i < cardDTOS.size(); i++)
                        if (rightdetail.getAscriptionCardId().equals(cardDTOS.get(i).getCardId()))//找出对应的卡，回显对应卡的下标
                            rightdetail.setJumpIndex(i);
                }

                boolean isHave = false;//判断会员是否拥有过此权益，默认为false

                List<CustomerRightdetailDTO> customerRightdetails = new ArrayList<>();//把会员拥有的权益筛选提取出来
                List<Integer> removeIndexs = new ArrayList<>();//保存一下index，用于处理完之后删除元素，减轻循环压力
                if (customerRightdetailDTOS != null && isAscription) {//用户有这张卡&&该权益属于该卡
                    for (int i = 0; i < customerRightdetailDTOS.size(); i++) {
                        if (customerRightdetailDTOS.get(i).getRightdetailId().equals(rightdetail.getRightdetailId())) {//匹配与当前权益匹配的用户权益
                            isHave = true;
                            removeIndexs.add(i);
                            if (customerRightdetailDTOS.get(i).getRightdetailState().equals(CustomerConstants.valid.getValue()))//进一步筛选出可用的
                                customerRightdetails.add(customerRightdetailDTOS.get(i));
                        }
                    }
                }

                if (rightdetail.getCouponType()!=null)
                {
                    switch (rightdetail.getCouponType()) {
                        case "CouponTypeFullMinus":
                        case "CouponTypeCashCoupon":
                        case "CouponTypeDiscount":
                        case "CouponTypeAdmissionTicket":
                            rightdetail.setRightdetailIntroduce(rightdetail.getNumberOfTimes() + "张");
                            if (isHave)
                                rightdetail.setRightdetailSurplusIntroduce(customerRightdetails.size() + "张");
                            break;
                        case "CouponTypeRegister":
                        case "CouponTypeTest":
                        case "CouponTypeFlightDelay":
                        case "CouponTypeFlightDCancellation":
                            rightdetail.setRightdetailIntroduce(rightdetail.getNumberOfTimes() + "次");
                            if (isHave)
                                rightdetail.setRightdetailSurplusIntroduce(customerRightdetails.size() + "次");
                            break;
                        case "CouponTypeInfiniteRegister":
                        case "CouponTypeInfiniteConsultation":
                        case "CouponTypeDoctor":
                            rightdetail.setRightdetailIntroduce("无限次");
                            if (isHave)
                                if (customerRightdetails.size() > 0)
                                    rightdetail.setRightdetailSurplusIntroduce("无限次");
                            break;
                        case "CouponTypeCommodity":
                        case "CouponTypeTravel":
                            rightdetail.setRightdetailIntroduce(rightdetail.getCouponMoney() + "元");
                            if (isHave)
                                if (customerRightdetails.size() > 0)
                                    rightdetail.setRightdetailSurplusIntroduce(customerRightdetails.get(0).getCouponMoney() + "元");
                                else
                                    rightdetail.setRightdetailSurplusIntroduce("0元");
                            break;
                        case "CouponTypeVIPHall":
                            rightdetail.setRightdetailIntroduce("本人" + rightdetail.getNumberOfTimes() + "次");
                            if (isHave)
                                rightdetail.setRightdetailSurplusIntroduce("本人" + customerRightdetails.size() + "次");
                            break;
                        case "CouponTypeInfiniteVIPHall":
                            rightdetail.setRightdetailIntroduce("本人无限次");
                            if (isHave)
                                if (customerRightdetails.size() > 0)
                                    rightdetail.setRightdetailSurplusIntroduce("本人无限次");
                            break;
                        case "CouponTypeDD":
                            rightdetail.setRightdetailIntroduce(rightdetail.getNumberOfTimes() + "张");
                            if (isHave) {
                                rightdetail.setLogoUrl(rightdetail.getLogoTowUrl());
                                rightdetail.setReceive(true);
                                rightdetail.setRightdetailSurplusIntroduce(customerRightdetails.size() + "张");
                            } else
                                rightdetail.setReceive(false);
                            break;
                        case "CouponTypeCommodityReceive":
                            rightdetail.setRightdetailIntroduce(rightdetail.getCouponMoney() + "元");
                            if (isHave) {
                                rightdetail.setLogoUrl(rightdetail.getLogoTowUrl());
                                rightdetail.setReceive(true);
                                if (customerRightdetails.size() > 0)
                                    rightdetail.setRightdetailSurplusIntroduce(customerRightdetails.get(0).getCouponMoney() + "元");
                                else
                                    rightdetail.setRightdetailSurplusIntroduce("0元");
                            } else
                                rightdetail.setReceive(false);
                            break;
                    }
                }

                if (customerRightdetailDTOS != null && customerRightdetailDTOS.size() != 0)
                    for (int i = removeIndexs.size() - 1; i >= 0; i--)
                        customerRightdetailDTOS.remove(removeIndexs.get(i));//删除元素减轻循环压力
                rightdetail.setHave(isHave);
            }
            card.setRightdetailNum(rightdetailNum);
            /*已为您节约多少钱的规则：
1、客户使用的贵宾厅，安检按销售价*使用次数计算金额；（按照非会员的价格统计）
2、给客户开通的510万综合交通意外险，价值多少钱？（售价150元）
3、航班延误理赔的钱；（没有取消了，延误按照每次300元，赔4次，那就是1200元）
4、使用的商品兑换券的金额；
5、使用的旅游抵扣券的金额；（看以后的旅游订单，会员本人节约2800，随行节约2200）
6、使用的出行抵扣券的金额；
7、使用的积分金额，按各业务实际抵扣金额算；
8、使用的优惠券金额；
9、提供服务的VIP经理价值多少钱？（300元/天）
10、景区门票卡价值多少钱？（98元/年）
11、体检价值多少钱？（1299元/次）
12、挂号价值多少钱？（200元/次）
13、家庭医生价值多少钱？（399元/年）
14、使用的滴滴代驾券金额
15、使用的机票选座服务，每次价值多少钱？（30元/次）*/
            card.setSavePrice(new BigDecimal(999));
        }
        for (CardDTO card : cardDTOS) {
            if (card.getCardLevel().equals(cardLevel))
                card.setLevel(true);
        }
        return cardDTOS;
    }

    @Override
    public CardDTO selectCardAndRightDetailById(Long cardId) {

        return cardMapper.selectCardAndRightDetailById(cardId);
    }
}
